package com.team.order.controller;

import com.team.common.core.web.controller.BaseController;
import com.team.common.core.web.domain.AjaxResult;
import com.team.common.log.annotation.Log;
import com.team.common.log.enums.BusinessType;
import com.team.common.security.annotation.RequiresPermissions;
import com.team.order.domain.dto.OrderSubmitDTO;
import com.team.order.utils.PaymentUtil;
import com.team.order.service.IAppOrderService;
import com.team.order.domain.Order;
import com.team.order.service.IAdminOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 梁国瑞
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/app/order")
@RequiredArgsConstructor
@Validated
public class AppOrderController extends BaseController {

    private final IAppOrderService orderService;
    private final PaymentUtil paymentUtil;
    private final IAdminOrderService adminOrderService;

    /*提交订单接口*/
    @RequiresPermissions("order:order:add")
    @Log(title = "用户订单", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitOrder(@Valid @RequestBody OrderSubmitDTO dto) {
        int i = orderService.submitOrder(dto);
        if (i <= 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }
    
    /**
     * 立即支付（使用模拟支付）
     */
    @Log(title = "订单支付", businessType = BusinessType.UPDATE)
    @PostMapping("/pay")
    public AjaxResult payOrder(@RequestParam String orderNo) {
        try {
            boolean success = paymentUtil.simulatePaymentSuccess(orderNo);
            if (success) {
                log.info("订单支付成功，订单号：{}", orderNo);
                return AjaxResult.success("支付成功");
            } else {
                return AjaxResult.error("支付失败");
            }
        } catch (Exception e) {
            log.error("订单支付失败，订单号：{}", orderNo, e);
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 查询支付状态
     */
    @GetMapping("/pay/status/{orderNo}")
    public AjaxResult queryPayStatus(@PathVariable String orderNo) {
        try {
            String status = paymentUtil.queryPaymentStatus(orderNo);
            log.info("查询支付状态，订单号：{}，状态：{}", orderNo, status);
            return AjaxResult.success(status);
        } catch (Exception e) {
            log.error("查询支付状态失败，订单号：{}", orderNo, e);
            return AjaxResult.error(e.getMessage());
        }
    }
    
    /**
     * 取消支付
     */
    @Log(title = "取消支付", businessType = BusinessType.UPDATE)
    @PostMapping("/pay/cancel/{orderId}")
    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelPay(@PathVariable Long orderId) {
        try {
            // 先将订单支付状态设为未支付
            Order order = new Order();
            order.setId(orderId);
            order.setPayStatus(0L); // 0-未支付
            adminOrderService.updateOrder(order);
            // 这里可以调用订单服务取消订单，然后清除支付状态
            boolean success = paymentUtil.simulatePaymentFail(orderId.toString());
            if (success) {
                log.info("取消支付成功，订单ID：{}", orderId);
                return AjaxResult.success("取消支付成功");
            } else {
                return AjaxResult.error("取消支付失败");
            }
        } catch (Exception e) {
            log.error("取消支付失败，订单ID：{}", orderId, e);
            return AjaxResult.error(e.getMessage());
        }
    }
}
